﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Core.Log;
using Unity.VisualScripting;
using UnityEngine;

namespace Core.CSV
{
    public abstract class TBBaseInterface {
        protected Dictionary<uint, TBBaseConfig> mDic;
        public int Capacity => mDic.Count;

        public TBBaseInterface() {
            mDic = new Dictionary<uint, TBBaseConfig>();
        }

        public abstract void AddData(params object[] p);

        public T GetRow<T>(uint id) where T :TBBaseConfig{
            if (!mDic.ContainsKey(id)) {
                return null;
            }
            return mDic[id] as T;
        }
    }
    public abstract class TBBaseConfig { }
    /// <summary>
    /// CSV工具类
    /// </summary>
    public partial class CSVMgr : Util.Singleton<CSVMgr>
    {
        public static T LoadCSV<T>() where T : TBBaseInterface,IFileReader,new()
        {
            T inf = new T();
            string filePath = Application.dataPath + inf.Directory + inf.FileName;
            
            StreamReader sr = null;
            sr = System.IO.File.OpenText(filePath);
            string line;
            //第一行是注释
            line = sr.ReadLine();
            if (line == null) return inf;
            //第二行是属性
            line = sr.ReadLine();
            if (line == null) return inf;
            string[] types = line.Split(',');
            object[] objs = new object[types.Length];
            while ((line = sr.ReadLine()) != null)
            {
                string[] values = line.Split(',');
                for (int i = 0; i < values.Length; ++i)
                {
                    objs[i] = TryParse(types[i], values[i]);
                }
                inf.AddData(objs);
            }

            return inf;
        }


        public static object TryParse(string type, string value)
        {
            switch (type)
            {
                case "int":
                    return int.Parse(value);
                case "float":
                    return float.Parse(value);
                case "string":
                    return value;
                case "uint":
                    return uint.Parse(value);
                case "bool":
                    return bool.Parse(value);
                default:
                    ADbg.LogEF("数据类型{0} 不存在",type);
                    return null;
            }
        }
    }
}